﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhiStore.Threading;

namespace FileSystemAnalysis.Code
{
    class Consumer: Boostable
    {
        private Channel<ResultCapsule> inputChannel;
        private Model model;

        private Dictionary<string, List<string>> files;
        private ulong filesShaed = 0L;

        public Consumer(Channel<ResultCapsule> inputChannel, Model model)
        {
            this.inputChannel = inputChannel;
            this.model = model;
            this.files = new Dictionary<string, List<string>>();
        }

        public void Run()
        {
            try
            {
                while (true)
                {
                    ResultCapsule res = inputChannel.Receive();
                    if (!files.ContainsKey(res.sha256))
                        files.Add(res.sha256, new List<string>());

                    files[res.sha256].Add(res.path);
                    model.FilesShaed = filesShaed++;
                }
            }
            catch (PoisonException)
            {
                //all files indexed
            }
            model.Shaing = false;

            foreach (string sha in files.Keys)
            {
                if (files[sha].Count > 1)
                    for(int i = 1; i < files[sha].Count; i++)
                        model.addRow(files[sha][i], sha);
            }

            model.Running = false;
        }
    }
}
